// pages/goods_detail/index.js
import { request } from "../../request/index"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { goods_id } = options;
    request({
      url: '/goods/detail?goods_id=' + goods_id
    }).then(res => {
      this.setData({
        goodsList: {
          pics: res.data.message.pics,
          goods_introduce: res.data.message.goods_introduce.replace(/\.webp/g, '.jpg'),
          cat_id: res.data.message.cat_id,
          goods_price: res.data.message.goods_price,
          goods_name: res.data.message.goods_name,
          goods_num: 1
        }
      })
    })
  },
  swiperTap(e) {
    const current = e.currentTarget.dataset.operation;
    const urls = this.data.goodsList.pics.map(item => {
      return item.pics_big_url
    });
    wx.previewImage({
      current,
      urls,
    });
  },
  addCart(e) {
    let { operation } = e.currentTarget.dataset;
    operation.goods_introduce = "";
    let y = operation.pics.slice(0,1);
    operation.pics = y;
    operation.checked = true;
    let cart = wx.getStorageSync("cart") || [];
    if(JSON.stringify(cart) === '[]'){
      cart.push(operation)
    }else{
      cart.forEach(res => {
        if (res.cat_id === operation.cat_id) {
          res.goods_num++;
        } else {
          cart.push(operation)
        }
      })
    }
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: '添加成功',
      mask: true,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})